import 'dart:math';

import 'package:flutter/material.dart';
import 'package:shining_red_star/model/unique.dart';
import 'package:shining_red_star/widgets/choice_question.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

import '../utils/play.dart';
import '../utils/random.dart';

class ChoiceQuestionPractice<T extends Unique> extends StatefulWidget {
  final List<T> totalOptions;
  final Widget tip;
  final String tipAud;
  final Widget Function(T answer, List<T> options, bool hasFocus)
      renderQuestion;
  final Widget Function(T option, bool hasFocus) renderOption;
  final String Function(T answer, List<T> options) getQuestionAud;

  const ChoiceQuestionPractice({
    super.key,
    required this.totalOptions,
    required this.tip,
    required this.tipAud,
    required this.renderQuestion,
    required this.renderOption,
    required this.getQuestionAud,
  });

  @override
  State<ChoiceQuestionPractice> createState() =>
      _ChoiceQuestionPracticeState<T>();
}

class _ChoiceQuestionPracticeState<T extends Unique>
    extends State<ChoiceQuestionPractice<T>> {
  List<String> historyAnswerIdList = [];
  AudioPlayManager audPlayer = AudioPlayManager();
  bool ready = false;
  List<T> options = [];
  late T answer;
  bool loading = true;

  void getNext() {
    List<T> nextOptions = getRandomItems(widget.totalOptions, 4);
    T nextAnswer = nextOptions[Random().nextInt(nextOptions.length)];
    while (historyAnswerIdList.contains(nextAnswer.id)) {
      nextOptions = getRandomItems(widget.totalOptions, 4);
      nextAnswer = nextOptions[Random().nextInt(nextOptions.length)];
    }
    if (historyAnswerIdList.length >= widget.totalOptions.length / 2) {
      historyAnswerIdList.removeAt(0);
    }
    historyAnswerIdList.add(nextAnswer.id);
    setState(() {
      options = nextOptions;
      answer = nextAnswer;
      loading = false;
    });
  }

  @override
  void initState() {
    super.initState();
    getNext();
    audPlayer.mediaPlay(widget.tipAud).whenComplete(() {
      setState(() {
        ready = true;
      });
    });
  }

  @override
  void dispose() {
    audPlayer.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!ready) {
      return Center(
        child: widget.tip,
      );
    }
    if (loading) {
      return Center(
        child: const TDLoading(
          size: TDLoadingSize.large,
          icon: TDLoadingIcon.circle,
        ),
      );
    }
    return ChoiceQuestion<T>(
      renderQuestion: widget.renderQuestion,
      options: options,
      answer: answer,
      renderOption: widget.renderOption,
      getQuestionAud: widget.getQuestionAud,
      nextQuestion: getNext,
      onAnswered: (isRight) {
        if (isRight) {
          Future.delayed(Duration(seconds: 1), () {
            setState(() {
              loading = true;
              WidgetsBinding.instance.addPostFrameCallback((_) {
                getNext();
              });
            });
          });
        }
      },
    );
  }
}
